package com.itheima.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.MyException.HaveStudentException;
import com.itheima.mapper.ClazzMapper;

import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    ClazzMapper cm;
    @Autowired
    StudentMapper sm;
    //条件查询所有班级
    @Override
    public PageResult<Clazz> getClazz(ClazzQueryParam cqp) {
        PageHelper.startPage(cqp.getPage(),cqp.getPageSize());
        System.out.println(cqp.getPageSize());
        List<Clazz> clazzList=cm.list(cqp);
        //班级状态处理
        for(Clazz c1 :clazzList){
            if(c1.getEndDate().isBefore(LocalDate.now())){
                c1.setStatus("已结课");
            }else
                c1.setStatus("正在进行中");
        }
        Page<Clazz> p=(Page) clazzList;
        return new PageResult<Clazz>(p.getTotal(),p.getResult());
    }

    //新增班级
    @Override
    public void addclazz(Clazz c) {
        c.setUpdateTime(LocalDateTime.now());
        c.setCreatTime(LocalDateTime.now());
        cm.addclazz(c);
    }
    //修改数据的查询回显 根据id查询班级
    @Override
    public Clazz idfind(Integer id) {

        return cm.idfind(id);
    }
//修改数据
    @Override
    public void updateclazz(Clazz c) {
        c.setUpdateTime(LocalDateTime.now());
        cm.updateclass(c);
    }
//删除数据
    @Override
    public void deleteclazz(Integer id) throws HaveStudentException {
    //只需要去抛出异常，剩下的处理交给全局异常处理器。提前在异常类中编写好异常的处理方式
         List<Student> studentList= sm.getStudentList(id);
        if (!(studentList.isEmpty())){
            /*抛出自定义异常的时候需要注意，会被java自动包装成InvocationTargetException
            异常，需要在全局异常处理器中重新拆包*/
            throw new HaveStudentException("该班级下尚有学生，不能删除该班级！");
        }else {
            cm.deleteclazz(id);
        }
    }
    //学生管理在新增学院的时候展示所有的班级
    @Override
    public List<Clazz> getclazzlist() {
        return cm.getclazzlist();
    }
}
